package com.example.bankmanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.example.bankmanage.Common.UserContext;
import com.example.bankmanage.constant.StatusUsers;
import com.example.bankmanage.convention.exception.ClientException;
import com.example.bankmanage.dto.rep.*;
import com.example.bankmanage.dto.resq.BillExcelRespDTO;
import com.example.bankmanage.entity.PageBean;
import com.example.bankmanage.entity.accounts;
import com.example.bankmanage.entity.bills;
import com.example.bankmanage.mapper.AccountMapper;
import com.example.bankmanage.service.AccountService;
//import com.example.bankmanage.util.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.example.bankmanage.convention.errorcode.UserErrorCodeEnum.ACCOUNT_SAVE_ERROR;

@Service
@SuppressWarnings("all")
@Slf4j
public class AccountServiceimpl extends ServiceImpl<AccountMapper, accounts> implements AccountService  {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    public PageBean fetchAccountList(String accountNumber, String accountType, Integer pageNum, Integer pageSize, String status) {
//        System.out.println(UserContext.getUsername());
        PageHelper.startPage(pageNum,pageSize);
        Page<accounts> page = accountMapper.fetchAccountList(accountNumber,accountType,status);
        System.out.println(page);
        PageBean pageBean = new PageBean();
        pageBean.setTotalElements(page.getTotal());
        pageBean.setContent(page.getResult());
        return pageBean;
    }

    @Override
    public void updateAccount(Integer accountId, AccountUpdateReqDTO requestParam) {
        accounts account = BeanUtil.toBean(requestParam, accounts.class);
        account.setAccountId(null); // 防止主键被更新
        LambdaUpdateWrapper<accounts> updateWrapper = Wrappers.lambdaUpdate(accounts.class)
                .eq(accounts::getAccountId,accountId);
        baseMapper.update(account,updateWrapper);
    }

    @Override
    public void addAccount(AccountAddReqDTO requestParam) {
        int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, accounts.class));
        if(inserted < 1){
            throw new ClientException(ACCOUNT_SAVE_ERROR);
        }
    }

    @Override
    public GetAccountDetailReqDTO getAccountDetail(Integer accountId) {
        LambdaQueryWrapper<accounts> QueryWrapper = Wrappers.lambdaQuery(accounts.class)
                .eq(accounts::getAccountId, accountId);
        accounts account = baseMapper.selectOne(QueryWrapper);
        if(account == null)throw new ClientException("账户不存在");
        GetAccountDetailReqDTO requestParam = BeanUtil.toBean(account,GetAccountDetailReqDTO.class);
        return requestParam;
    }

    @Override
    public void exportAccount(AccountExportReqDTO exportDTO, OutputStream outputStream) {
        // 1. 查询数据
        List<accounts> account = accountMapper.selectAccountsForExport(exportDTO);
//        System.out.println(bills);
        if (CollectionUtils.isEmpty(account)) {
            throw new RuntimeException("没有可导出的数据");
        }

        // 2. 导出Excel
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .build()) {

            WriteSheet writeSheet = EasyExcel.writerSheet("账单数据")
                    .head(AccountExportReqDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(
                            getHeaderStyle(),
                            getContentStyle())) // 自定义样式
                    .build();

            // 3. 数据转换并写入Excel
            excelWriter.write(convertToExcelVO(account), writeSheet);
            System.out.println(excelWriter);
            excelWriter.finish(); // 确保写入完成
        }
    }

    private List<accounts> convertToExcelVO(List<accounts> account) {
        return account.stream().map(bill -> {
            AccountExportReqDTO vo = new AccountExportReqDTO();
            // 这里进行属性拷贝
            BeanUtils.copyProperties(bill, vo);
            // 特殊字段处理
            vo.setStatus(String.valueOf(bill.getStatus()));
            return bill;
        }).collect(Collectors.toList());
    }
    // 内容单元格样式
    private WriteCellStyle getContentStyle() {
        WriteCellStyle style = new WriteCellStyle();

        // 1. 对齐方式
        style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);   // 垂直居中

        // 2. 边框设置
        style.setBorderLeft(BorderStyle.THIN);          // 左边框
        style.setBorderRight(BorderStyle.THIN);         // 右边框
        style.setBorderTop(BorderStyle.THIN);           // 上边框
        style.setBorderBottom(BorderStyle.THIN);        // 下边框
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 边框颜色
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());

        // 3. 背景色（默认白色，可不设置）
        style.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());

        // 4. 字体样式
        WriteFont font = new WriteFont();
        font.setFontName("宋体");                       // 字体
        font.setFontHeightInPoints((short) 11);        // 字号
        font.setColor(IndexedColors.BLACK.getIndex()); // 字体颜色
        style.setWriteFont(font);

        // 5. 自动换行（根据需求）
        style.setWrapped(true);

        return style;
    }
    // 自定义表头样式
    private WriteCellStyle getHeaderStyle() {
        WriteCellStyle style = new WriteCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 其他样式设置...
        return style;
    }
}
